package com.cliang.servlet;

import com.cliang.tools.db.DB;
import com.cliang.entity.BlogUser;
import com.cliang.tools.Tools;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class AddBlogServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");

        String title=req.getParameter("title");
        String author=req.getParameter("author");
        String type=req.getParameter("type");
        String content=req.getParameter("editorValue");
        String msg="";
        PrintWriter printWriter=resp.getWriter();
        HttpSession session=req.getSession();
        BlogUser blogUser= (BlogUser) session.getAttribute("blogUser");

        Connection conn= DB.getConnection();
        if(conn!=null){
            try {
                PreparedStatement psmt=conn.prepareStatement("insert into Blog.blog(B_uid, B_tid, B_title,B_author, B_content,B_time) VALUES (?,?,?,?,?,?)");
                psmt.setInt(1,blogUser.getBuId());
                psmt.setInt(2,Integer.parseInt(type));
                psmt.setString(3,title);
                psmt.setString(4,author);
                psmt.setString(5,content);
                psmt.setString(6, Tools.getCurrentDate());
                psmt.executeUpdate();
                msg="添加成功！";
            } catch (SQLException e) {
                msg="系统内部错误，请稍后再试！";
                e.printStackTrace();

            }
            DB.close(conn);
        }else {
            msg="系统内部错误，请稍后再试！";
        }

        printWriter.write(msg);
    }
}
